package com.dynamic.mybatis.core.generator.method;

import com.baomidou.mybatisplus.core.toolkit.sql.SqlInjectionUtils;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import com.dynamic.mybatis.core.generator.InjectorHelper;
import com.dynamic.mybatis.core.generator.InjectorMethod;
import com.dynamic.mybatis.core.generator.MapperMethod;
import com.dynamic.mybatis.core.metadata.DynamicMappedStatement;
import com.dynamic.mybatis.core.metadata.MappedStatementField;
import com.dynamic.mybatis.core.metadata.MappedStatementMetaField;
import com.dynamic.mybatis.core.metadata.MappedStatementTable;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.session.Configuration;

import java.util.Map;
import java.util.Optional;

/**
 * @Description
 * @Author xs
 * @Date 2023/4/20 11:06
 */
public class Save extends InjectorMethod {

    public Save() {
        super(MapperMethod.StandardMapperMethod.save);
    }

    public Save(MapperMethod mapperMethod) {
        super(mapperMethod);
    }

    @Override
    public String builderScriptSql(String namespace, MappedStatementTable table, MapperBuilderAssistant assistant) {

        Insert insert =  getByMapperMethod(MapperMethod.StandardMapperMethod.insert.name());

        String insertSql = insert.builderScriptSql(namespace,table,assistant);

        UpdateById updateById =  getByMapperMethod(MapperMethod.StandardMapperMethod.updateById.name());

        String updateSql = updateById.builderScriptSql(namespace,table,assistant);


        Optional<MappedStatementMetaField> firstKeyField = InjectorHelper.getFirstKeyField(table);

        String keyProperty = firstKeyField.isPresent() ? firstKeyField.get().getField() : null;


        String sql =   SqlScriptUtils.convertChoose(String.format("%s != null", keyProperty),SPACE + replaceScriptTag(updateSql),NEWLINE + SPACE +replaceScriptTag(insertSql) + NEWLINE);

        return sql;
    }

    @Override
    public DynamicMappedStatement injectMappedStatement(String namespace, MappedStatementTable table, MapperBuilderAssistant assistant) {
        LanguageDriver languageDriver = assistant.getConfiguration().getDefaultScriptingLanguageInstance();
        Configuration configuration = assistant.getConfiguration();

        String sql = builderScriptSql(namespace,table,assistant);

        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Map.class);


        Optional<MappedStatementMetaField> optionalField = InjectorHelper.getFirstKeyField(table);
        String keyProperty = null;
        String keyColumn = null;
        KeyGenerator keyGenerator = NoKeyGenerator.INSTANCE;
        // 表包含主键处理逻辑,如果不包含主键当普通字段处理
        if (optionalField.isPresent()) {
            MappedStatementField field  = optionalField.get();
            if (field.isAutoincrement()) {
                /* 自增主键 */
                keyGenerator = Jdbc3KeyGenerator.INSTANCE;
                keyProperty = field.getField();
                // 去除转义符
                keyColumn = SqlInjectionUtils.removeEscapeCharacter(field.getColumn());
            }
        }
         MappedStatement ms =  super.addMappedStatement(assistant,table,namespace,sqlSource, SqlCommandType.UPDATE, Map.class,null,Integer.class,keyGenerator,keyProperty,keyColumn);
         return builderDynamicMappedStatement(namespace,table,ms,sql);
    }
}